package com.cow.horse.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cow.horse.common.Result;
import com.cow.horse.config.interceptor.AuthAccess;
import com.cow.horse.entity.Message;
import com.cow.horse.service.IMessageService;
import com.cow.horse.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 留言板管理 前端控制器
 * </p>
 *
 * @author 欧怡伶
 * @since 2024-05-21
 */
@RestController
@RequestMapping("/message")
public class MessageController {

    @Resource
    private IMessageService messageService;

    private final String now = DateUtil.now();

    // 新增或者更新
    @PostMapping
    public Result save(@RequestBody Message message) {
        if (message.getId() == null) {
            message.setTime(now);
            message.setUser(TokenUtils.getCurrentUser().getNickname());
            message.setUserId(TokenUtils.getCurrentUser().getId());
        }
        messageService.saveOrUpdate(message);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        messageService.removeById(id);
        return Result.success();
    }

    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        messageService.removeByIds(ids);
        return Result.success();
    }

    @GetMapping
    public Result findAll() {
        return Result.success(messageService.list());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(messageService.getById(id));
    }

    @AuthAccess
    @GetMapping("/front")
    public Result findAllMessages() {
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        List<Message> list = messageService.list(queryWrapper);
        return Result.success(list);
    }

    @GetMapping("/user")
    public Result findByUser() {
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", TokenUtils.getCurrentUser().getId());
        return Result.success(messageService.list(queryWrapper));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String name) {
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        if (!"".equals(name)) {
            queryWrapper.like("content", name);
        }
        return Result.success(messageService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }
}